#include "SoftPWM.h"


void SFPwm_Init(
    SFPwm_t *pwmst ,
    volatile unsigned int * _port 
)  
{
    pwmst->port = _port;
    for(uint8_t i=0;i<SOFTPWM_CHANEL;++i){
        pwmst->cnt[i] = 0 ;
#if (SOFTPWM_ARR_INDEPENDENCE==1)
        pwmst->ARR[i] = 0XFFFF ;
#endif 
    }

#if (SOFTPWM_ARR_INDEPENDENCE!=1)
    pwmst->ARR[0] = 0xFFFF ;
#endif 
    pwmst->RST_VALUE = 0;
    pwmst->enable = 0 ;
}

void SFPwm_Polarity(SFPwm_t *pwmst , uint32_t value) {
    pwmst->RST_VALUE = value;
}
void SFPwm_Enable(SFPwm_t *pwmst , uint8_t chanel ,uint8_t isEna) {
    if(isEna)pwmst->enable |= 1u<<chanel ;
    else pwmst->enable &= ~(1u<<chanel) ;
}

void SFPwm_ARR(SFPwm_t *pwmst , uint8_t chanel , uint16_t value){
#if (SOFTPWM_ARR_INDEPENDENCE==1)
    pwmst->ARR[chanel] = value ;
#else
    pwmst->ARR[0] = value ;
#endif 
}

void SFPwm_CCR(SFPwm_t *pwmst , uint8_t chanel , uint16_t value){
    pwmst->CCR[chanel] = value ; 
}

void SFPwm_Yield(SFPwm_t *pwmst) {
#if (SOFTPWM_ARR_INDEPENDENCE==1)
    uint32_t out = 0 ;
    for(uint8_t i=0;i<SOFTPWM_CHANEL;++i) {
        if((pwmst->enable >> i)&0x1){
            if(pwmst->cnt[i]>=pwmst->ARR[i]) pwmst->cnt[i] = 0 ;
            else pwmst->cnt[i]++ ;

            if(pwmst->cnt[i] >= pwmst->CCR[i]) {
                out |= 1u<<i ;
            } 
        } 
    }
    *pwmst->port = out ^ pwmst->RST_VALUE ;
#else 
    uint32_t out = 0 ;
    for(uint8_t i=0;i<SOFTPWM_CHANEL;++i) {
        if((pwmst->enable >> i)&0x1){
            if(pwmst->cnt[i]>=pwmst->ARR[0]) pwmst->cnt[i] = 0 ;
            else pwmst->cnt[i]++ ;

            if(pwmst->cnt[i] >= pwmst->CCR[i]) {
                out |= 1u<<i ;
            } 
        }
    }
    *pwmst->port = out ^ pwmst->RST_VALUE ;
#endif

}
 

